package com.slixils.demo.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * @Author: JinChongLi
 * @Description:
 * @Date: Created in 4:21 2022/4/11
 * @ModOfied By:
 */
public class Json {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static <T> T fromJson(String json,Class<T> clazz){
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static <T> List<T> fromJsonList(String json, Class<T> baseType){
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, baseType);
        try {
            List<T> o = objectMapper.readValue(json, javaType);
            return o;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
